// utils/auth.js
const app = getApp()

// 检查是否已登录
const checkLogin = () => {
  return !!app.globalData.token
}

// 获取用户信息
const getUserInfo = () => {
  return new Promise((resolve, reject) => {
    if (!app.globalData.token) {
      reject(new Error('用户未登录'))
      return
    }
    
    app.request('/users/profile', 'GET')
      .then(res => {
        app.globalData.userInfo = res.data
        resolve(res.data)
      })
      .catch(reject)
  })
}

// 微信登录
const wechatLogin = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: (res) => {
        if (res.code) {
          app.request('/auth/wechat-login', 'POST', { code: res.code })
            .then(result => {
              app.globalData.token = result.data.token
              app.globalData.userInfo = result.data.user
              wx.setStorageSync('token', result.data.token)
              resolve(result)
            })
            .catch(reject)
        } else {
          reject(new Error('微信登录失败'))
        }
      },
      fail: reject
    })
  })
}

// 获取手机号
const getPhoneNumber = (e) => {
  return new Promise((resolve, reject) => {
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      reject(new Error('获取手机号失败'))
      return
    }
    
    app.request('/auth/phone-login', 'POST', {
      code: '',
      phone_code: e.detail.code
    })
      .then(resolve)
      .catch(reject)
  })
}

// 退出登录
const logout = () => {
  app.globalData.token = null
  app.globalData.userInfo = null
  wx.removeStorageSync('token')
  
  wx.showToast({
    title: '已退出登录',
    icon: 'success'
  })
  
  setTimeout(() => {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  }, 1500)
}

// 需要登录的操作包装器
const requireLogin = (fn) => {
  return function(...args) {
    if (!checkLogin()) {
      wx.showModal({
        title: '请先登录',
        content: '此功能需要登录后使用',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            })
          }
        }
      })
      return
    }
    return fn.apply(this, args)
  }
}

module.exports = {
  checkLogin,
  getUserInfo,
  wechatLogin,
  getPhoneNumber,
  logout,
  requireLogin
}